package yxy.game.pm2.module.avatar;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import yxy.apple.util.PubSub.MethodSubscriber;
import yxy.apple.util.PubSub.SubscriptionMethod;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.title;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.pubsub.CurrencyPublisher;
import yxy.game.pm2.bean.pubsub.CurrencyPublisher.CurrencySubscription;
import yxy.game.pm2.module.NotificationHandle;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.playtype.PlayTypeHandle;
import yxy.game.pm2.module.playtype.PlayTypeModule;

public class TitleSubscriber extends MethodSubscriber {
	static private TitleSubscriber instance;

	public static TitleSubscriber getInstance() {
		if (instance == null) {
			instance = new TitleSubscriber();
			instance.init();
		}
		return instance;
	}

	private void init() {
		CurrencyPublisher.getInstance().subscribe(this);
	}

	private TitleSubscriber() {
	}

	@SubscriptionMethod(Type = CurrencySubscription.class)
	public void receive(CurrencySubscription subscription) {
//		System.err.println("订阅更新Task");
		String playerCode = subscription.getPlayerCode();
		if (!subscription.checkTypes(allowType())) {
			return;
		}
		PlayerBean playerBean = PlayerBean.get(playerCode);
		Collection<Currency> currencies = subscription.getCurrencies();
		if (subscription.isAdd()) {
			// 称号激活
			for (Currency currency : currencies) {
				if (currency.getType().equals(CurrencyType.CT_称号)) {
					title _title = DataCenter.getData(currency.getDataId(), title.class);
					if (_title == null) {
						continue;
					}
					TitleModule.add(playerCode, _title);
					PlayTypeHandle.saveTitle(playerCode, PlayTypeModule.get(playerCode));
					new BattleHandle().powerUpdate(playerBean.getCode());
				}
			}
		} else {
			try {
				if (playerBean.tryLock()) {
					// 称号剥夺
					for (Currency currency : currencies) {
						if (currency.getType().equals(CurrencyType.CT_称号)) {
							title _title = DataCenter.getData(currency.getDataId(), title.class);
							if (_title == null) {
								continue;
							}
							if (playerBean.getTitle() == _title.getId()) {

								playerBean.setTitle(0);
								playerBean.set();

								new NotificationHandle().notifyPlayerTitle(playerBean);
								PlayTypeHandle.saveTitle(playerCode, PlayTypeModule.get(playerCode));
								new BattleHandle().powerUpdate(playerBean.getCode());

							}

						}
					}
				}
			} catch (Exception e) {
			} finally {
				playerBean.unlock();
			}
		}
	}

	private Set<CurrencyType> allowTypes;

	private Set<CurrencyType> allowType() {
		if (allowTypes != null) {
			return allowTypes;
		}
		allowTypes = new HashSet<>();

		allowTypes.add(CurrencyType.CT_称号);

		return allowTypes;
	}
}
